<?php
namespace app\front\service\v2;
use app\front\model\WithdrawOrder as WithdraworderModel;
use app\front\service\GetMsgService;
class WithdrawOrder extends GetMsgService
{
    
    private static $_instance;
    
    //private 构造函数
    private function __construct() {
        // echo " I'm construct! process id is " . getmypid() . " and thread id is " . Thread::getCurrentThreadId() . "\n";
    }
    
    private function __clone() {
        //    echo " I'm clone! process id is " . getmypid() . " and thread id is " . Thread::getCurrentThreadId() . "\n";
    }
    
    //单例方法访问类实例
    public static function getInstance() {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }  
    /**
     * 函数用途描述 : 调用此方法将使数据库中未提现用户提现
     * @date: 2018年1月29日 上午10:55:09
     * @author: 孙洪亮
     * @param:  $limit每分钟执行数
     * @return:
     */
    public function timedTaskPayForMember(){ 
        // $name =$WithdrawOrder->where('status=0')->field('weixin')->find();
        $limit=5;//每分钟执行数
        $users = WithdraworderModel:: where('status=0')->order('create_time')->limit($limit)->field('id,name,shop_id,money,weixin')->select();
        $users=json_decode(json_encode($users),true);
        for($i=0;$i<count($users);$i++)
        {
          
            //将$user赋值为当前指针
            $user=$users[$i];
            logs("user.txt", $user);
            $id=$user['id'];//当前第一个元素
            $name= $user['name'];//当前第二个元素
            $openid= $user['weixin'];//当前最后一个元素
            $amount=  $user['money'];//当前倒数第二个元素
           if($this->checkWithdraw($name)){
               echo is_array($user);
               $user['status']=3;
               $user['update_time']=date("Y-m-d H:i:s",time());
               logs("USER.TXT", $user);
               WithdraworderModel:: where('id',$id)->update($user);
              
              echo json_encode("一分钟内不允许重复提现！",true); 
           }else{
               if($name && $amount && $openid)
               {
                   $retuen_params=$this->PayForMember($amount, $name, $openid);
                   $user= json_decode(json_encode($user),true);
                   if($retuen_params['return_code'] == 'SUCCESS' && $retuen_params['result_code'] == 'SUCCESS')
                   {
                       $user['status']=1;
                       $user['update_time']=date("Y-m-d H:i:s",time());
                       WithdraworderModel:: where('id',$id)->update($user);
                   }else{
                       $user['status']=2;
                       $user['update_time']=date("Y-m-d H:i:s",time());
                       WithdraworderModel:: where('id',$id)->update($user);
                   }
               }else{
                   $user['status']=2;
                   $user['update_time']=date("Y-m-d H:i:s",time());
                   WithdraworderModel:: where('id',$id)->update($user);
               }
           }
          
          
        }
 
    }
    
    public  function MemberWithdraw($userMsg, $WithdrawMoney){
        $openid=$this->getOpenId();
        $retuen_params=  $this->PayForMember($WithdrawMoney, $name=null, $openid,$NoCheck=true);
        logs("MemberWithdraw.txt", $retuen_params);     
        if($retuen_params['return_code']=='SUCCESS' && $retuen_params['result_code']=='SUCCESS'){
            return $retuen_params;
        }else{
            return $retuen_params['err_code_des'];
        }
    }
    
    
    public function PayForMember($amount,$name=null,$openid,$NoCheck=false){
        $partner_trade_no=makeOrderNo();
        $amount=$amount*100;
        //获取企业转账个人所需参数
        $params=$this->getPayForMemberXml($partner_trade_no, $amount,$name,$openid,$NoCheck);
        //         //参数信息存入日志
        //         $this->logs('log_PayForMember.txt',date("Y-m-d H:i:s",time()).$params);
        //向转账URL发送参数
        $retuen_params= postStr(config('PayForMemberUrl'),$params);
        logs('log_return_PayForMember.txt',$retuen_params);
        return XmlToArr($retuen_params);
        //将返回值记录日志
        
    }
    
  
    
    /**
     * 函数用途描述 :企业向个人付款的xml参数准备
     * @date: 2018年2月6日 上午9:09:44
     * @author: 孙洪亮
     * @param:  $partner_trade_no（商户订单号），$amount(付款金额) $name(付款对象的真实姓名）,$openid（付款对象的openid）
     * @return: null
     */
    public function getPayForMemberXml($partner_trade_no,$amount,$name,$openid,$NoCheck=false){
        $check_name='FORCE_CHECK';
        if($NoCheck){
            $check_name='NO_CHECK';
        }
        $params = [
            'mch_appid' =>config('appid'),//微信分配的账号ID（企业号corpid即为此appId）
            'mchid' =>config('mch_id'),//商户号
            'nonce_str' => createNonceStr(),//随机字符串
            'partner_trade_no' =>$partner_trade_no,//商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
            'openid' =>$openid,//用户openid
            'check_name' =>$check_name,//红包发放总人数
            're_user_name' =>$name,//收款用户真实姓名。 如果check_name设置为FORCE_CHECK，则必填用户真实姓名
            'amount' =>$amount,//企业付款金额，单位为分
            'desc' =>config('desc'),//企业付款操作说明信息。必填
            'spbill_create_ip' =>config('client_ip'),// 调用接口的机器Ip地址
        ];
        
        $params['sign'] = getSign($params);//加入签名
        return ArrToXml($params);
    }
    
   
    
}

